<template>
  <div class="app-page">
    <el-table-form ref="form">
      <el-form-item class="merge-item">
        <el-select v-model="qType" style="width: 170px; margin-right: 2px;">
          <el-option label="客户名称" value="csmName" />
          <el-option label="客户电话" value="contactPhone" />
          <el-option label="客户编号" value="csmCode" />
          <el-option label="备注" value="remark" />
        </el-select>
        <el-input v-model="csmText" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="单号">
        <el-input v-model="query.orderCode" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="批发类型">
        <el-select v-model="wsaleType" placeholder="请选择">
          <el-option
            v-for="item in wsaleTypeBottleMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :table-form-merge="2" class="merge-item">
        <el-select v-model="query.timeType" style="width: 170px; margin-right: 2px;">
          <el-option label="登记时间" value="1" />
          <el-option label="结单时间" value="2" />
        </el-select>
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="责任机构" prop="orgSNNo">
        <el-tree-select
          v-model="query.orgSNNo"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择组织机构',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item class="merge-item">
        <el-select v-model="user_qtype" style="width: 170px; margin-right: 2px;">
          <el-option value="transactId" label="登记人" />
          <el-option value="ownerId" label="结单人" />
        </el-select>
        <el-select v-model="user_qtype_value" :loading="$loadingPlugin.getOwnerList" placeholder="请选择">
          <el-option
            v-for="item in ownerList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="单据状态" prop="orderStatus">
        <el-select v-model="query.orderStatus" placeholder="请选择">
          <el-option
            v-for="item in orderStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付方式">
        <el-select v-model="query.paymentMethod" placeholder="请选择">
          <el-option
            v-for="item in paymentMethodMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button type="primary" icon="el-icon-plus" @click="add">新增</el-button>
        <el-button type="primary" icon="el-icon-printer" @click="print">打印</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      :row-class-name="tableRowClassName"
      custom-column
      @fetch="fetchData"
    />
    <statement-bottle ref="statementBottle" />
    <add-bottle-order ref="addbottleorder" />
  </div>
</template>

<script>
  import { queryOwnersList, bottleSalesQueryList, saveLorryOrderUpdate } from '@/api'
  import moment from 'dayjs'
  import { formatColumnMap, parseTime } from '@/utils'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import AddBottleOrder from './components/AddBottleOrder'
  import StatementBottle from './components/StatementBottle'

  export default {
    name: 'tab-bottle',
    components: {
      StatementBottle,
      AddBottleOrder
    },
    data() {
      return {
        mode: 1,
        treeData: [],
        wsaleTypeBottleMap: [{ 'value': 1, 'desc': '预约批发', 'key': 'TYPE1' }, { 'value': 2, 'desc': '上门批发', 'key': 'TYPE2' }],
        orderStatusMap: [{ 'value': -1, 'desc': '已作废', 'key': 'DELETE' }, { 'value': 2, 'desc': '未结单', 'key': 'NOPAY' }, { 'value': 10, 'desc': '已结单', 'key': 'PAY' }, { 'value': 12, 'desc': '已冲红', 'key': 'DO' }],
        paymentMethodMap: [{ 'value': 1, 'desc': '现金', 'key': 'MONEY' }, { 'value': 2, 'desc': '微信支付', 'key': 'WECHAT' }, { 'value': 16, 'desc': '月结', 'key': 'YJ' }, { 'value': 128, 'desc': '支付宝', 'key': 'ALIPAY' }, { 'value': 256, 'desc': '预付卡', 'key': 'CSMCARD' }, { 'value': 512, 'desc': '国志钱包', 'key': 'ICBCEPAY' }, { 'value': 1024, 'desc': '工行支付', 'key': 'ICBCPAY' }],
        user_qtype: 'transactId',
        qType: 'csmName',
        csmText: '',
        wsaleType: '',
        user_qtype_value: '',
        date: [moment().endOf('hour'), moment().endOf('hour')],
        query: {
          timeType: '1',
          orgSNNo: '',
          orderCode: '',
          orderStatus: '',
          paymentMethod: '',
          wsaleFlag: '1'
        },
        ownerList: [],
        tableData: {
          total: 0,
          column: [
            {
              prop: 'orderCode',
              width: 160,
              label: '单号',
              render: (h, { row }) => <el-link onClick={() => this.openDetail(row)}>{row.orderCode}</el-link>
            },
            {
              prop: 'csmCode',
              label: '客户编号'
            },
            {
              prop: 'csmName',
              label: '客户名称'
            },
            {
              prop: 'csmAddress',
              width: 200,
              label: '客户地址'
            },
            {
              prop: 'contactPhone',
              width: 100,
              label: '联系电话'
            },
            {
              prop: 'orgName',
              width: 200,
              label: '责任机构'
            },
            {
              prop: 'wsaleType',
              label: '批发类型',
              render: (h, { row }) => <span>{ row.wsaleType && formatColumnMap(this.wsaleTypeBottleMap, 'value', row.wsaleType, 'desc') }</span>
            },
            {
              prop: 'weight1',
              align: 'right',
              label: '空车重(吨)',
              render: (h, { row }) => <span>{ row.weight1 ? (row.weight1 / 1000).toFixed(5) : '' }</span>
            },
            {
              prop: 'weight2',
              align: 'right',
              label: '重车重(吨)',
              render: (h, { row }) => <span>{ row.weight2 ? (row.weight2 / 1000).toFixed(5) : '' }</span>
            },
            {
              prop: 'totalNetWeight',
              align: 'right',
              label: '实收净重(吨)',
              render: (h, { row }) => <span>{ row.totalNetWeight ? (row.totalNetWeight / 1000).toFixed(5) : '' }</span>
            },
            {
              prop: 'weight3',
              align: 'right',
              label: '盈余量(吨)',
              render: (h, { row }) => <span>{ row.weight3 === 0 ? '0.00000' : (row.weight3 / 1000).toFixed(5) }</span>
            },
            {
              prop: 'tReceivables',
              align: 'right',
              label: '订单金额'
            },
            {
              prop: 'decimalSpare1',
              align: 'right',
              label: '运费'
            },
            {
              prop: 'paymentMethod',
              label: '支付方式',
              render: (h, { row }) => <span>{ row.paymentMethod === 0 ? '' : formatColumnMap(this.paymentMethodMap, 'value', row.paymentMethod, 'desc') }</span>
            },
            {
              prop: 'tAccReceivable',
              align: 'right',
              label: '支付金额'
            },
            {
              prop: 'transactTime',
              width: 160,
              label: '登记时间',
              render: (h, { row }) => <span>{ row.transactTime && parseTime(row.transactTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'transactor',
              label: '登记人'
            },
            {
              prop: 'signDt',
              width: 160,
              label: '结单时间',
              render: (h, { row }) => <span>{ row.signDt && parseTime(row.signDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'ownerName',
              label: '结单人'
            },
            {
              prop: 'remark',
              label: '备注'
            },
            {
              prop: 'orderStatus',
              label: '单据状态',
              render: (h, { row }) => <span>{ row.orderStatus && formatColumnMap(this.orderStatusMap, 'value', row.orderStatus, 'desc') }</span>
            },
            {
              label: '操作',
              align: 'center',
              fixed: 'right',
              width: 90,
              render: (h, { row, $index }) => {
                return (
                  <div>
                    {row.orderStatus === 2 && <el-link size='mini' onClick={() => this.openStatementBottle(row, $index)}>结单</el-link>}
                    {row.orderStatus === 2 && <el-link size='mini' type='danger' onClick={() => this.del(row, $index)}>作废</el-link>}
                    {row.orderStatus === 10 && <el-link size='mini' onClick={() => this.bottleUpdate(row, $index)}>冲红</el-link>}
                  </div>
                )
              }
            }
          ],
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList'
      ])
    },
    async created() {
      await this.getTreeData()
    },
    methods: {
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构,查询登记人/结单人
      selectTreeChange(value) {
        const martchOrg = this.orgList.find(item => item.orgSNNo === value.orgSNNo)
        this.getOwnerList(martchOrg.orgId)
      },
      async getOwnerList(orgId) {
        // const b = corpsetting.sp1 >> 2 & 0x01
        const res = await queryOwnersList({
          orgId
          // corpparm1: b
        })
        this.ownerList = res.data
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const params = {
          ...this._getQuery(this.query),
          pageIndex: currentPage,
          pageSize
        }
        params[this.qType] = this.csmText
        params.wsaleType = this.wsaleType ? this.wsaleType : '-1'
        if (this.query.timeType === '1') {
          if (this.date && this.date.length === 2) {
            params['transactDtStart'] = moment(this.date[0]).format()
            params['transactDtEnd'] = moment(this.date[1]).format()
          }
        } else {
          if (this.date && this.date.length === 2) {
            params['signDtStart'] = moment(this.date[0]).format()
            params['signDtEnd'] = moment(this.date[1]).format()
          }
        }
        if (this.user_qtype_value) {
          params[this.user_qtype] = this.user_qtype_value
        }
        if (!this.query.orderStatus) {
          params.orderStatus = 0
        }
        console.log('this.query.paymentMethod', this.query.paymentMethod)
        if (!this.query.paymentMethod) {
          params['paymentMethod'] = '-1'
        }
        // console.log('入参', params)
        const res = await bottleSalesQueryList(params)
        // console.log('结果', res)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      // 点击单号
      async openDetail(row) {
        this.$refs.statementBottle.open(row, 'bottle', 1)
      },
      async add() {
        await this.$refs.addbottleorder.open()
        // this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 点击结单
      async openStatementBottle(row) {
        await this.$refs.statementBottle.open(row, 'bottle')
      },
      // 点击作废
      del(row, index) {
        this.$confirm('确认作废当前瓶批单？', '提示', {
          type: 'warning'
        }).then(async() => {
          const { status } = await saveLorryOrderUpdate({
            orderCode: row.orderCode,
            orderStatus: -1
          })
          console.log('ssssss', status)
          if (status === 200) {
            this.$message({
              type: 'success',
              message: '作废瓶批单成功！'
            })
            this.$refs.lbTable.fetch({ currentPage: 1 })
          }
        })
      },
      // 点击冲红
      bottleUpdate(row) {
        this.$confirm('确认冲红当前槽批单？', '提示', {
          type: 'warning'
        }).then(async() => {
          const { status } = await saveLorryOrderUpdate({
            orderCode: row.orderCode,
            orderStatus: 12
          })
          console.log('ssssss', status)
          if (status === 200) {
            this.$message({
              type: 'success',
              message: '冲红槽批单成功！'
            })
            this.$refs.lbTable.fetch({ currentPage: 1 })
          }
        })
      },
      async print() {
        console.log('打印')
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 设置行类名
      tableRowClassName({ row }) {
        if (row.orderStatus === -1) { // 说明作废
          return 'deleted-row'
        } else if (row.orderStatus === 12) { // 说明冲红
          return 'reverse-row'
        }
        return ''
      }
    }
  }
</script>

<style lang="scss" scoped>
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
/deep/ .el-table tr.deleted-row {
  background: #ffdedf;
}
/deep/ .el-table tr.reverse-row {
  background: #f66;
}
</style>
